import random
import time
import uuid

from flask import Blueprint, request, send_file, jsonify, redirect
from application.models.users.user import *
from application.tools.myredis import r
from application.tools.myjwt import myjwt
from application.tools.comm import sendMsg, get_ali_object
import json

course_blue = Blueprint("courseblue", __name__)

@course_blue.route("/addCourse",methods=['POST'])
def addCourse():
    try:
        # 获取参数
        data = json.loads(request.data)
        # 写入课程表
        course = Course(name=data['name'],url=data['url'],descrip=data['desc'],ctype=data['type'])
        db.session.add(course)
        # 获取新加的课程id
        scourse = Course.query.filter(Course.name == data['name']).first()
        # 写入课程标签表
        for i in data['tags']:
            # 查询标签表
            # tag = Tags.query.filter(Tags.id == i).first()
            # scourse.tags.append(tag)
            sql = "insert into course_tag(courseid,tagid) values(%d,%d)"%(scourse.id,int(i))
            db.session.execute(sql)
        # 课程分类表
        for i in data['ctype']:
            sql = "insert into course_cate(courseid,course_typeid) values(%d,%d)"%(scourse.id,int(i))
            db.session.execute(sql)
        db.session.commit()
    except:
        db.session.rollback()
    return jsonify({'code':200})

# import math
# @course_blue.route("/getCourse")
# def getCourse():
#     # 获取参数page
#     page = int(request.args.get("page"))
#     #获取上线、即将上线
#     online = int(request.args.get('is_publish'))
#     # 获取类别
#     types = int(request.args.get("types"))
#     # 查询总条数
#     if types == 0:
#         total = Course.query.filter(Course.is_publish == online).count()
#     else:
#         total = Course.query.filter(Course.is_publish==online,Course.ctype==types).count()
#     # 定义每页显示多少条
#     page_size = 2
#     # 查询当前页记录
#     start = math.ceil((page-1)*page_size)
#     # select * Course.query.offset start,page_size
#     # 获取排序字段
#     orderpara = request.args.get('orderpara')
#     if orderpara == 'new':
#         if types == 0:
#             course = Course.query.order_by(Course.create_time.desc()).filter(Course.is_publish==online).offset(start).limit(page_size).all()
#         else:
#             course = Course.query.order_by(Course.create_time.desc()).filter(Course.is_publish == online,Course.ctype==types).offset(start).limit(page_size).all()
#     else:
#         course = Course.query.order_by(Course.views.desc()).filter(Course.is_publish == online).offset(start).limit(page_size).all()
#     print("====================",course)
#     list = [{
#         "id":i.id,
#         "name":i.name,
#         "url":i.url,
#         "views":i.views
#     }for i in course]
#     # 返回结果
#     return jsonify({"code":200,"clist":list,"total":total,"page_size":page_size})

import math
@course_blue.route("/getCourse")
def getCourse():
    # 获取当前页面
    page = int(request.args.get("page"))
    page_size = 2
    # 获取条件
    #获取上线、即将上线
    online = int(request.args.get('is_publish'))
    # 获取类别
    types = int(request.args.get("types"))
    # 获取标签
    tags = int(request.args.get("tags"))
    # 获取排序字段
    orderpara = request.args.get('orderpara')

    # 重构where条件
    where = "1=1"

    if online:
        where = where + " and c.is_publish=" + str(online)

    if types>0:
        where = where + " and c.ctype=" + str(types)

    # 排序
    orderby = " order by c.views desc"
    if orderpara == "new":
        orderby = " order by c.create_time desc"
    start = math.ceil((page-1)*page_size)
    # 查询一有多少条记录
    if tags > 0:
        countsql = "select count(c.id) as tcount from course as c inner join course_tag as ct on c.id=ct.courseid where ct.tagid="+str(tags)+" and "+where
    else:
        countsql = "select count(c.id) as tcount from course as c where " + where
    cres = db.session.execute(countsql)
    cdata = cres.fetchone()
    total = cdata['tcount']
    print(total)
    # 查询当前页记录
    if tags > 0:
        # sql = "select c.* from course as c inner join course_tag as ct on c.id=ct.courseid where is_publish=1 and ctype=1 and ct.tagid=1 order by c.create_time desc limit 0,2"
        sql = "select c.* from course as c inner join course_tag as ct on c.id=ct.courseid where ct.tagid=" + str(tags) + " and " + where + orderby + " limit " + str(start) + "," + str(page_size)
    else:
        sql = "select c.* from course as c where "+where+orderby+" limit "+str(start)+","+str(page_size)
    res = db.session.execute(sql)
    data = res.fetchall()
    list = [{
            "id":i.id,
            "name":i.name,
            "url":i.url,
            "views":i.views
    }for i in data]
    return jsonify({"code":200,"clist":list,"total":total,"page_size":page_size})

@course_blue.route("/getDetail")
def getDetail():
    # 获取id
    courseid = request.args.get("id")
    userid = request.args.get("userid")
    # 查询课程信息
    course = Course.query.filter(Course.id == courseid).first()
    # 加入浏览记录，获取到userid
    if userid:
        key = "collection" + str(userid) + "pro" + str(courseid)
        r.hash_add(key,"courseid",course.id)
        r.hash_add(key,"name",course.name)
        r.hash_add(key,"url",course.url)
    # 返回课程信息
    course = {
        "id":course.id,
        "name":course.name,
        "views":course.views,
        "tcount":course.tcount,
        "descrip":course.descrip
    }
    return jsonify({'code':200,"course":course})

@course_blue.route("/getViews")
def getViews():
    # 获取id
    userid = request.args.get("userid")
    findkey = "collection" + str(userid) + "*"
    gidlist = r.getvalues(findkey)
    reslist = []
    for i in gidlist:
        goods = r.getall_hash(i)
        dict = {}
        for k, v in goods.items():
            kk = k.decode()
            vv = v.decode()
            dict[kk] = vv
        reslist.append(dict)
    return jsonify({'code':200,"list":reslist})


# 加入购物车
@course_blue.route("/buy",methods=['POST'])
def buy():
    # 获取参数 userid courseid
    userid = request.args.get("userid")
    tcourseid = request.args.get("tcourseid")
    # 加减类型默认为+
    type = 1
    try:
        type = request.args.get("type")
    except:
        pass
    # 从hash中获取数据，如果存在数量+1, buy1course2
    key = "buy"+str(userid)+"course"+str(tcourseid)
    # 如果不存在存入redis hash
    flag = r.findkey_hash(key)
    # 存在
    if flag:
        # 数量+1
        ff = r.jiajian_hash(key,"number",1,type)
        if ff == False:
            return jsonify({'code':10010,"mes":"不能再减了"})
    else:
        r.hash_add(key,"id",tcourseid)
        r.hash_add(key,"number",1,)
        # 选中
        r.hash_add(key,"flag",'True')
    # 返回结果
    return jsonify({'code':200,"userid":userid,"tcourseid":tcourseid})

# 获取购物车
@course_blue.route("/mycart")
def mycart():
    # 获取参数userid
    userid = request.args.get("userid")
    # 从hash中获取商品id和数量
    key = "buy"+str(userid)+"*"
    goods = r.getvalues(key)
    glist = []
    tmoney = 0
    tcount = 0
    if goods:
        for i in goods:
            # 获取每一条商品的具体信息
            good = r.getall_hash(i)
            rescourse={}
            for k,v in good.items():
                params = k.decode()
                value = v.decode()
                if params == "id":
                    # 获取到的商品信息
                    tcourse = Tcourse.query.filter(Tcourse.id == value).first()
                    rescourse['id'] = tcourse.id
                    rescourse['name'] = tcourse.title
                    rescourse['url'] = tcourse.url
                    rescourse['price'] = float(tcourse.price)
                if params == 'number':
                    # 获取购买的数量
                    rescourse['number'] = value
                if params == 'flag':
                    if value == 'True':
                        rescourse['flag'] = True
                    else:
                        rescourse['flag'] = False
            # 小计
            rescourse["total"] = float(rescourse['price'])*float(rescourse['number'])
            # 总价
            if rescourse['flag'] == True:
                rescourse["total"] = float(rescourse['price']) * float(rescourse['number'])
                tmoney = float(tmoney)+float(rescourse['total'])
                # 总数
                tcount = int(tcount)+int(rescourse['number'])
            glist.append(rescourse)
    # 价格、图片、名字...从mysql中获取，从redis商品缓存中读取
    return jsonify({"code":200,"glist":glist,"tmoney":tmoney,"tcount":tcount})

# 生成订单
@course_blue.route("/create_orders",methods=['POST'])
def create_orders():
    # 接收参数userid
    data = json.loads(request.data)
    userid = int(data['userid'])
    # 接口幂等性验证
    order_token = data['order_token']
    print("**********",order_token)
    value = r.str_get(order_token)
    print("=========",value)
    if not value:
        return jsonify({'code':10010,"mes":"已经生成不能重复操作"})
    # 删除
    r.str_del(order_token)
    # 根据userid查询购物车
    key = "buy"+str(data['userid'])+"*"
    glist = r.getvalues(key)
    # 生成订单号
    order_no = str(random.randint(100,999))+str(data['userid'])
    totalmoney = 0
    try:
        if glist:
            # 写入订单表
            orders = Orders(order_no=order_no, userid=userid)
            db.session.add(orders)
            # 写入订单详情表
            for i in glist:
                flag = r.getone_hash(i,"flag")
                if flag:
                    flag = flag.decode()
                    if flag == 'True':
                        id = r.getone_hash(i,"id")
                        id = id.decode()
                        number = r.getone_hash(i,"number")
                        number = number.decode()
                        # 判断购物车中已选中的记录
                        tcourse = Tcourse.query.filter(Tcourse.id == id).first()
                        # 查询训练营课程表，判断库存
                        if int(tcourse.store) < int(number):
                            return jsonify({"code":200,'mes':"库存不够"})
                        # 写入订单详情表
                        tmoney = float(tcourse.price)*float(number)
                        detail = OrdersDetail(order_no=order_no,courseid=id,cname=tcourse.title,number=number,price=tcourse.price,tmoney=tmoney)
                        db.session.add(detail)
                        # 总价
                        totalmoney = totalmoney + tmoney
                        # 删除购物车已经选中的记录
                        # r.del_hash(i)
            orders.tmoney = totalmoney
            db.session.add(orders)
            db.session.commit()
            return jsonify({'code':200,'mes':"购买成功",'orderno':order_no})
    except:
        return jsonify({'code':10010,'mes':"购买失败"})

# 获取训练营课程
@course_blue.route("/getBootcamp")
def getBootcamp():
    # 查询训练营课程
    bootcamp = Tcourse.query.all()
    bootlist = [{
        "id":i.id,
        "title":i.title,
        "url":i.url,
        "price":i.price,
        "intro":i.intro
    }for i in bootcamp]
    # 返回数据
    return jsonify({"code":200,"bootlist":bootlist})


# 修改单个的选中状态
@course_blue.route('/modifyStatus')
def modifyStatus():
    # 获取参数 userid  goodsid
    userid = request.args.get('userid')
    cid = request.args.get('cid')
    # 获取原来的状态判断
    key = "buy"+str(userid)+'course'+str(cid)
    flag = r.getone_hash(key,'flag')
    cflag = 'True'
    if flag:
        flag = flag.decode()
        # 根据返回结果选择相反的值
        if flag == 'True':
            cflag = 'False'
    r.hash_add(key,'flag',cflag)
    return jsonify({'code':200})

# 修改全选的选中状态
@course_blue.route('/modifyAllStatus')
def modifyAllStatus():
    # 获取参数 userid  goodsid
    userid = request.args.get('userid')
    status = request.args.get('status')
    flag = 'false'
    if status == 'true':
        flag = "True"
    # 把当前用户购物车全部改为选中状态
    keys = r.getvalues("buy"+str(userid)+"*")
    for i in keys:
        r.hash_add(i,'flag',flag)
        print(flag)
    return jsonify({'code':200})



@course_blue.route("/get_order_token")
def get_order_token():
    # 生成uuid
    token = uuid.uuid1().hex
    print(token)
    #将token存入redis
    r.str_add(token,'1')
    # 返回结果
    return jsonify({'code':200,'token':token})


@course_blue.route("/orders")
def orders():
    # order_no
    order_no = request.args.get('order_no')
    # sql = "select orders.order_no,orders.tmoney,od.* from orders inner join orders_detail as od on orders.order_no=od.order_no where orders.order_no=%d"%(int(order_no))
    # res = db.session.execute(sql)
    # list = res.fetchall()
    # print(list)
    # return 'ok'
    orderdict = {}
    orders = Orders.query.filter(Orders.order_no == order_no).first()
    if orders:
        orderdict["order_no"] = orders.order_no
        orderdict["tmoney"] = orders.tmoney
        list = []
        for i in orders.details:
            list.append({"courseid":i.courseid,"cname":i.cname,"number":i.number,"price":i.price,"tmoney":i.tmoney})
        orderdict['details'] = list

    return jsonify({'code':200,"orders":orderdict})

# 支付宝支付
@course_blue.route("/buytcourse",methods=['POST'])
def buytcourse():
    # 订单号
    order_no = request.args.get('order_no')
    print("****************",order_no)
    orders = Orders.query.filter(Orders.order_no == order_no).first()
    print("****************", orders.tmoney)
    # 支付，返回支付url
    pay = get_ali_object()
        # 生成支付的url
    # 订单号重构充值1 支付订单2
    order_no = str(order_no)+":"+str(1)
    query_params = pay.direct_pay(
        subject="test",  # 商品简单描述
        out_trade_no=str(order_no),  # 用户购买的商品订单号（每次不一样） 20180301073422891
        total_amount=float(orders.tmoney),  # 交易金额(单位: 元 保留俩位小数)
    )
    pay_url = "https://openapi.alipaydev.com/gateway.do?{0}".format(query_params)  # 支付宝网关地址（沙箱应用）
    return jsonify({'code':200,'url':pay_url})
